import axios, {
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from "axios";
import { router } from "expo-router";
import runtimeConfig from "@/config/runtime";
import { ResponseCode } from "@/types/api-common";
import TokenManager from "@/utils/token-utils";
import * as Device from "expo-device";

interface CustomAxiosConfig extends AxiosRequestConfig {
  _retry?: boolean; // 用于标记是否正在重试
}

const api: AxiosInstance = axios.create({
  baseURL: runtimeConfig.API_BASE_URL, // API 地址
  withCredentials: true, // 允许携带 cookie
  timeout: 10000,
});

api.interceptors.request.use(
  async (config: any) => {
    // 从 SecureStore 获取 token
    const token = TokenManager.getToken();
    if (token) {
      config.headers = config.headers || {};
      if (config.headers && typeof config.headers.set === "function") {
        config.headers.set("Authorization", `${token}`);
        config.headers.set("X-Device-Id", Device.osInternalBuildId);
      } else {
        config.headers.Authorization = `${token}`;
      }
    }

    // const refreshToken = TokenManager.getRefreshToken();
    // if (refreshToken) {
    //     config.headers.Cookie = `refresh_token=${refreshToken}`;
    //     console.log("refresh_token: ", refreshToken)
    // }
    return config;
  },
  (error: AxiosError) => {
    return Promise.reject(error);
  }
);

// 响应拦截器（统一错误处理）
api.interceptors.response.use(
  async (response: AxiosResponse) => {
    const { data, config, headers } = response;
    // 0. 检查响应头中是否有token
    const authorization: string = headers["authorization"];
    // 0.1 检查响应头中是否有 set-cookie
    // const setCookie: string = headers["set-cookie"][0];

    // 1. 响应头中有token则 更新 token
    if (authorization) {
      TokenManager.setToken(authorization);
      return response;
    }

    // 1.1 响应头中有set-cookie则 更新 refreshToken
    // if (setCookie) {
    //     TokenManager.setRefreshToken(setCookie)
    // }

    // 2. accessToken 过期/非法 => 自动刷新
    if (
      data.code === ResponseCode.TOKEN_EXPIRED ||
      data.code === ResponseCode.NOT_TOKEN_ERROR ||
      data.code === ResponseCode.NO_AUTH_ERROR
    ) {
      const originalRequest = config as CustomAxiosConfig;
      if (!originalRequest._retry) {
        originalRequest._retry = true;
        try {
          const response = await refreshToken();
          const newToken = response.headers["Authorization"];
          if (response.headers["Authorization"]) {
            TokenManager.setToken(newToken);
            originalRequest.headers.Authorization = newToken;
          }
          return api(originalRequest);
        } catch (e) {
          return Promise.reject(e);
        }
      }
    }

    // 3. refreshToken 也失效了 或者 未登陆
    if (
      data.code === ResponseCode.NOT_LOGIN_ERROR ||
      data.code === ResponseCode.REFRESH_TOKEN_EXPIRED
    ) {
      router.replace("/login");
      await TokenManager.clearToken();
      // TokenManager.clearRefreshToken();
      return Promise.reject(data);
    }

    // 4. 正常返回
    return response;
  },
  async (error: AxiosError) => {
    // 可以统一处理 5xx 等非业务异常
    console.error(error);
    return Promise.reject(error);
  }
);

// Token 刷新函数
export const refreshToken = async () => {
  const refreshToken = TokenManager.getRefreshToken();
  return api.get("/user/login/auth/refresh_token", {
    headers: {
      Cookie: `${refreshToken}`,
    },
  });
};

export default api;
